export function transformProvinceData(provinceData) {
  const [name, yearData] = provinceData;

  // 构建统计数据数组
  const statistics = [
    {
      name: "cost",
      unit: "元",
      yearlyData: convertYearlyData(yearData, "消费支出"),
    },
    {
      name: "edFund",
      unit: "万元",
      yearlyData: convertYearlyData(yearData, "教育经费"),
    },
    {
      name: "GDP",
      unit: "亿元",
      yearlyData: convertYearlyData(yearData, "GDP"),
    },
    {
      name: "income",
      unit: "元",
      yearlyData: convertYearlyData(yearData, "收入"),
    },
    {
      name: "employment",
      unit: "万人",
      yearlyData: convertYearlyData(yearData, "就业人数"),
    },
    {
      name: "population",
      unit: "万人",
      yearlyData: convertYearlyData(yearData, "人口"),
    }
  ];

  // 验证必要的统计数据是否存在且有效
  const requiredStats = ['GDP', 'employment', 'population'];
  const hasAllRequired = requiredStats.every(statName => {
    const stat = statistics.find(s => s.name === statName);
    return stat && stat.yearlyData.length > 0;
  });

  if (!hasAllRequired) {
    console.warn(`警告: ${name} 缺少必要的统计数据`);
  }

  return {
    name,
    type: getProvinceType(name),
    statistics,
  };
}

function convertYearlyData(yearData, field) {
  const data = Object.entries(yearData)
    .filter(([year]) => year.endsWith("年"))
    .map(([year, data]) => ({
      year: parseInt(year.replace("年", "")),
      value: data[field],
    }))
    .filter((item) => item.value !== null && !isNaN(item.value));

  return data;
}

function getProvinceType(name) {
  if (name.endsWith("自治区")) return "自治区";
  if (name.endsWith("特别行政区")) return "特别行政区";
  if (name.endsWith("市")) return "直辖市";
  return "省";
}